import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(title: const Text('button')),
      body: const MyAppBody(),
    ));
  }
}

class MyAppBody extends StatefulWidget {
  const MyAppBody({super.key});

  @override
  State<MyAppBody> createState() => _MyAppBodyState();
}

class _MyAppBodyState extends State<MyAppBody> {
  int num = 0;
  int perPage = 15;
  final originalItems = List<String>.generate(1000, (index) => 'Item$index');
  List items = [];
  @override
  Widget build(BuildContext context) {
    return demo();
  }

  @override
  void initState() {
    super.initState();
    setState(() {
      items.addAll((originalItems.getRange(num, num + perPage)));
      num = num + perPage;
    });
  }

  void loadMore() {
    setState(() {
      if ((num + perPage) > originalItems.length) {
        items.addAll(originalItems.getRange(num, originalItems.length));
      } else {
        items.addAll(originalItems.getRange(num, num + perPage));
      }
      num = num + perPage;
    });
  }

  Widget demo() {
    return NotificationListener<ScrollNotification>(
        onNotification: (ScrollNotification scrollInfo) {
          if (scrollInfo.metrics.pixels == scrollInfo.metrics.maxScrollExtent) {
            loadMore();
            return true;
          }
          return false;
        },
        child: ListView.builder(
            itemCount:
                (num <= originalItems.length) ? items.length + 1 : items.length,
            itemBuilder: (BuildContext ctx, int i) {
              return (i == items.length)
                  ? const Center(
                      heightFactor: 1,
                      child: Text('正在加载中...'),
                    )
                  : ListTile(
                      title: Text('${items[i]}'),
                    );
            }));
  }
}
